package com.chengqs.rapid.core.netty.processor.filter.error;

import com.chengqs.rapid.common.constants.ProcessorFilterConstants;
import com.chengqs.rapid.common.enums.ResponseCode;
import com.chengqs.rapid.common.exception.RapidBaseException;
import com.chengqs.rapid.core.context.Context;
import com.chengqs.rapid.core.context.RapidResponse;
import com.chengqs.rapid.core.netty.processor.filter.AbstractEntryProcessorFilter;
import com.chengqs.rapid.core.netty.processor.filter.Filter;
import com.chengqs.rapid.core.netty.processor.filter.FilterConfig;
import com.chengqs.rapid.core.netty.processor.filter.ProcessorFilterType;

/**
 * <B>主类名称：</B>DefaultErrorFilter<BR>
 * <B>概要说明：</B>enter<BR>
 *
 * @author: chengqs
 * @create: 2025-03-17 21:03:31
 **/
@Filter(
        id = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ID,
        name = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_NAME,
        value = ProcessorFilterType.ERROR,
        order = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ORDER
)
public class DefaultErrorFilter extends AbstractEntryProcessorFilter<FilterConfig> {

    public DefaultErrorFilter() {
        super(FilterConfig.class);
    }

    @Override
    public void entry(Context context, Object... args) throws Throwable {
        try {
            Throwable throwable = context.getThrowable();
            ResponseCode responseCode = ResponseCode.INTERNAL_ERROR;
            if(throwable instanceof RapidBaseException) {
                RapidBaseException rapidBaseException = (RapidBaseException)throwable;
                responseCode = rapidBaseException.getCode();
            }
            RapidResponse rapidResponse = RapidResponse.buildRapidResponse(responseCode);
            context.setResponse(rapidResponse);
        } finally {
            System.err.println("============> do error filter <===============");
            // 设置写回标记
            context.written();
            // 触发后面的过滤器执行
            super.fireNext(context, args);
        }
    }
}
